
/**
 * Sphere
 * @version 1.0
 * @since 1.0
 * <p>
 * Created by Murphy at 2021/7/9 15:50
 **/
#include "Sphere.hpp"

namespace Stitches
{

bool Sphere::hit(const Ray &r, double t_min, double t_max, HitRecord &rec) const
{
    Vec3f oc = r.origin() - mCenter;
    double a = glm::dot(r.direction(), r.direction());
    double half_b = dot(r.direction(), oc);
    double c = glm::dot(oc, oc) - mRadius * mRadius;
    double discriminant = half_b * half_b - a * c;
    if (discriminant > 0)
    {
        double root = sqrt(discriminant);
        double t = (-half_b - root) / a;
        if (t > t_min && t < t_max)
        {
            rec.t = t;
            rec.p = r.at((float) t);
            Vec3f outWardNormal = (rec.p - mCenter) / (float) mRadius;
            rec.setFaceNormal(r, outWardNormal);
            rec.mat_ptr = mMat;
            return true;
        }
        t = (-half_b + root) / a;
        if (t > t_min && t < t_max)
        {
            rec.t = t;
            rec.p = r.at((float) t);
            Vec3f outWardNormal = (rec.p - mCenter) / (float) mRadius;
            rec.setFaceNormal(r, outWardNormal);
            rec.mat_ptr = mMat;
            return true;
        }
    }
    return false;
}
}